package com.ittx.dzt.tiktok.handler;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ittx.dzt.business.PlatformConstant;
import com.ittx.dzt.business.constant.StoreExtendConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.handler.AbstractBasePlatformApiHandler;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.mq.core.queue.producer.RocketmqProducer;
import com.ittx.dzt.okhttp.core.HttpRequestTemplate;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.SpringUtil;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.ittx.dzt.tiktok.util.TiktokUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class AbstractBaseTiktokApiHandler<T> extends AbstractBasePlatformApiHandler<T> {


	// 取值字段
	public static final String DATA_FIELD = "data";
	/**
	 * 查询总数
	 */
	public static final String RESULT_TOTAL = "total_count";
	public static String YMDHMS = "yyyy-MM-dd HH:mm:ss";
	@Autowired
	protected RocketmqProducer rocketmqProducer;

	@Override
	public String getPlatformCode() {
		return PlatformConstant.TIKTOK;
	}

	/**
	 * 执行API请求通用方法
	 *
	 * @param storeConfig 店铺配置
	 * @param paramMap    请求参数
	 * @param requestId   请求id
	 * @return 请求结果
	 */
	public Result executeTiktokApi(String url, StoreConfigDTO storeConfig, Map<String, Object> paramMap, String body, String requestId, String httpMethod) {
		long timestamp = System.currentTimeMillis() / 1000;
		paramMap.put("timestamp", timestamp);
		paramMap.put("app_key", storeConfig.getAppKey());
		// 计算签名
		String signVal = TiktokUtil.sign(storeConfig.getAppKey(), storeConfig.getAppSecret(), url, paramMap, body);
		// 发起请求
		Result result = null;
		try {
			url = storeConfig.getSdkUrl() + url;

			result = fetch(url, storeConfig, httpMethod, paramMap, body, signVal, requestId);
			if (result.isSuccess()) {
				Map<String, Object> resultMap = JacksonTool.toMap(result.getData());
				int code = (int) resultMap.get("code");
				if (code != 0) {
					String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getTiktokMethod(), result.getData());
					log.error(msg);
					return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(resultMap.get("code") + "-" + resultMap.get("message"));
				}
				return Result.success().addData(resultMap);
			}
			return result;
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getTiktokMethod(), e.getMessage());
			ExceptionLog.error(e, PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getTiktokMethod(), e.getMessage());
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(msg);
		}
	}

	/**
	 * 公共HTTP请求平台API
	 *
	 * @param storeConfig 店铺配置
	 * @param httpMethod  http请求方法
	 * @param params      请求参数
	 * @param body        请求body
	 * @param sign        请求签名
	 * @return 请求结果
	 * @throws IOException
	 */
	private Result fetch(String url, StoreConfigDTO storeConfig, String httpMethod, Map<String, Object> params, String body, String sign, String requestId) throws IOException {

		Map<String, String> reqParams = new HashMap<>();
		reqParams.put("sign", sign);
		if (MapUtil.isNotEmpty(params)) {
			for (Map.Entry<String, Object> e : params.entrySet()) {
				reqParams.put(e.getKey(), String.valueOf(e.getValue()));
			}
		}
		Map<String, String> headers = new HashMap<>();
		headers.put("x-tts-access-token", storeConfig.getSessionKey());
		headers.put("content-type", "application/json");
		HttpRequestTemplate httpRequestTemplate = SpringUtil.getBean(HttpRequestTemplate.class);

		if (httpRequestTemplate == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0006_MSG, HttpRequestTemplate.class.getName());
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0006, msg));
		}
		log.debug("请求参数url:{} reqMap:{}  body:{} headers:{}", url, JacksonTool.toJson(reqParams), body, JacksonTool.toJson(headers));
		String returnMsg;
		if (StringUtils.equalsIgnoreCase("GET", httpMethod)) {
			returnMsg = httpRequestTemplate.get(url, reqParams, headers);
		} else {
			returnMsg = httpRequestTemplate.postJsonParams(url, body, reqParams, headers);
		}
		log.debug("returnMsg:{}", returnMsg);
		if (StrUtil.isEmpty(returnMsg) || !JSONUtil.isTypeJSON(returnMsg)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0012_MSG, requestId, this.getPlatformCode()
					, this.getTiktokMethod(), url, returnMsg);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0012, msg));
		}
		return Result.success().addData(returnMsg);
	}

	/**
	 * 获取tiktok平台api
	 *
	 * @return tiktok平台API
	 * @date 2022/5/5 15:01
	 */
	public abstract String getTiktokMethod();

	/**
	 * 获取总页数
	 *
	 * @param totalCount 总记录数
	 * @param pageSize   每页显示记录数
	 * @return 总页数
	 */
	public Integer totalPage(Integer totalCount, Integer pageSize) {
		if (totalCount <= pageSize) {
			return 1;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	public Long totalPage(Long totalCount, Long pageSize) {
		if (totalCount <= pageSize) {
			return 1L;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	public String getDefaultUrl(StoreConfigDTO storeConfig) {
		String methodPath = this.getTiktokMethod();
		return methodPath;
	}

	/**
	 * 从扩展数据获取店铺密码
	 *
	 * @param platformApiParamDTO
	 * @return
	 */
	public String getShopCipher(PlatformApiParamDTO platformApiParamDTO) {
		return (String) TiktokUtil.getExtendValue(platformApiParamDTO.getExtendMap(), StoreExtendConstant.TIKTOK_STORE_CIPHER);
	}

	public Result<?> checkShopCipherInfo(PlatformApiParamDTO platformApiParamDTO) {
		String shopCipher = getShopCipher(platformApiParamDTO);
		if (StrUtil.isEmpty(shopCipher)) {
			return Result.error("平台店铺参数shop_cipher获取失败,请检查拓展参数tiktokStoreCipher");
		}
		return Result.success();
	}
}
